﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Logger;
using Cofe.Web.Utils;

namespace Cofe.Web.Feed
{
    public class FeedLinkHelper<T> : IFeedLinkHelper<T> 
        where T : EventArgs
    {
        private IFeedService<T> _feedService;
        public FeedLinkHelper(IFeedService<T> feedService)
        {
            _feedService = feedService;
        }

        public SyndicationLink createLink(UriTemplate template, string rel, string id)
        {
            Uri baseAddress = IncludeBaseAddress ? UrlUtils.BaseAddress : new Uri("http://dummy.org", UriKind.Absolute);
            var uri = template.BindByPosition(baseAddress, id);
            if (!IncludeBaseAddress)
                return new SyndicationLink(new Uri(uri.PathAndQuery, UriKind.Relative), rel, null, null, 0);
            return new SyndicationLink(uri, rel, null, null, 0);
        }

        public SyndicationLink CreateFeedLink(LinkType linkType, FeedId feedId)
        {            
            return createLink(_feedService.Builder.FeedTemplate, linkType.ToString(), feedId.Id.ToString());
        }

        public SyndicationLink CreateEventLink(LinkType linkType, IEventLog<T> eventLog, Guid eventLogId)
        {
            return createLink(_feedService.Builder.EventTemplate, linkType.ToString(), eventLogId.ToString());
        }

        public SyndicationLink CreateEntryLink(LinkType linkType, Guid entryId)
        {
            return createLink(_feedService.Builder.EntryTemplate, linkType.ToString(), entryId.ToString());
        }

        public bool IncludeBaseAddress { get; set; }
    }
}
